package com.mijie.homi.service.notify;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mijie.homi.common.domain.Notify;
import com.mijie.homi.dao.notify.NotifyDao;
import com.mijie.homi.dao.user.UserExtInfoDao;
import com.mijie.homi.listener.NotifyListener;

@Service
public class NotifyService {

	@Autowired
	private NotifyDao dao;
	@Autowired
	private NotifyListener listener;
	@Autowired
	private UserExtInfoDao userExtInfoDao;
	
	private static Logger logger = Logger.getLogger(NotifyService.class);
	
	public List<Notify> listNotifyByUserId(int userId){
		listener.pullNotify(userId);
		return dao.listNotifyByUserId(userId);
	}
	
	public int deleteNotify(int userId,String[] id){
		List<String> notifyIds = new ArrayList<String>();
		int maxSysMsgId = 0;
		for(int i = 0; i < id.length; i++){
			String tempId = id[i];
			if(tempId == null || "".equals(tempId)) continue;
				
			if(tempId.startsWith("sys_msg_")){
				int sysMsgId = Integer.parseInt(tempId.replaceAll("sys_msg_", ""));
				maxSysMsgId = Math.max(sysMsgId, maxSysMsgId);
			}else{
				notifyIds.add(tempId);
			}
		}
		int rows = 0;
		if(notifyIds.size() > 0)
			rows = dao.deleteNotify(userId, notifyIds.toArray(new String[notifyIds.size()]));
		
		if(maxSysMsgId > 0){
			Map<String, Integer> param = new HashMap<String, Integer>();
			param.put("userId", userId);
			param.put("systemMsgMark", maxSysMsgId);
			rows += userExtInfoDao.updateSysMsgMarkByUserId(param);
		}
		return rows;
	}
	
}
